import time
import logging

# 日志配置
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)

def api_logger(func):
    """API请求日志装饰器"""
    def wrapper(*args, **kwargs):
        # 记录请求开始
        start_time = time.time()
        logger.info(f"开始处理请求：{func.__name__}")

        try:
            # 执行原函数
            result = func(*args, **kwargs)

            # 记录请求成功
            end_time = time.time()
            logger.info(f"请求成功：{func.__name__}，耗时：{end_time - start_time:.2f}秒")
            return result

        except Exception as e:
            # 记录请求失败
            end_time = time.time()
            logger.error(f"请求失败：{func.__name__}，耗时：{end_time - start_time:.2f}秒，错误信息：{str(e)}")
            raise   # 重新抛出异常

    return wrapper

# 使用装饰器
@api_logger
def get_user_info(user_id):
    """获取用户信息"""
    time.sleep(1)   # 模拟网络请求
    if user_id <= 0:
        raise ValueError("用户ID不能小于等于0")
    return {"user_id": user_id, "name": f"用户_{user_id}"}

@api_logger
def update_user_profile(user_id,profile_data):
    """更新用户资料"""
    time.sleep(0.5) # 模拟网络请求
    return {"message": f"用户{user_id}的资料已更新", "status": "success"}

# 测试
try:
    user = get_user_info(12)
    print(f"获取用户：{user}")
    result = update_user_profile(12,{"name": "张三"})
    print(f"更新结果：{result}")

    # 异常情况
    get_user_info(-1)
except Exception as e:
    logger.error(f"捕获到异常： {e}")